define(['./initial'], function() {

    var app = angular.module('App.tool');
    app.factory('autoCompleteBoxHelper', function() {
        // 创建div和ul元素
        var box, ul;
        var isShow = false;

        function initialDom() {
            box = document.createElement('div');
            box.id = 'autoCompleteBox';
            box.className = 'autoCompleteBox';
            ul = document.createElement('ul');
            box.appendChild(ul);
        }

        //input dom List
        //记录已经绑定过的input dom id 和 event,以免再次绑定事件
        var domList = [];

        //是否是新的绑定项
        function getExistedDom(domId) {
            var list = domList.filter(function(item) {
                return item.id === domId;
            });
            if (list.length > 0) {
                return list[0];
            } else {
                domList.push({
                    id: domId,
                    func: null
                });
                return domList[domList.length - 1];
            }
        }

        // 实现接口，作为返回值
        var obj = {
            isShow: function() {
                return isShow;
            },
            "showAutoCompleteBox": function(para) {

                obj.closeAutoCompleteBox();
                if (!para.stringList || para.stringList.length === 0) {
                    return;
                }
                initialDom();
                // 当前选择项的序号
                var index = -1;

                // 按下方向键下
                var arrowDown = function() {
                    if (index >= para.stringList.length - 1)
                        return;
                    index++;
                    selectItem(index);
                };

                // 按下方向键上
                var arrowUp = function() {
                    if (index <= 0)
                        return;
                    index--;
                    selectItem(index);
                };

                // 高亮列表中的某一项
                var selectItem = function(index) {
                    if (index < 0 || index > ul.childNodes.length - 1)
                        return;
                    for (var i = 0; i < ul.childNodes.length; i++) {
                        ul.childNodes[i].className = '';
                    }
                    ul.childNodes[index].className = 'highlight';
                    // 如果此项不可见则滚动至可视范围
                    var top = ul.childNodes[index].offsetTop;
                    var bottom = top + ul.childNodes[index].clientHeight;
                    if (bottom > ul.scrollTop + ul.clientHeight)
                        ul.scrollTop = bottom - ul.clientHeight;
                    else if (top < ul.scrollTop)
                        ul.scrollTop = top;
                    // onItemSelected
                    para.onItemSelected(ul.childNodes[index].innerHTML);
                };

                // 清空列表内容
                ul.innerHTML = '';
                // 加载列表内容
                for (var i = 0; i < para.stringList.length; i++) {
                    var li = document.createElement('li');
                    li.innerHTML = para.stringList[i];
                    li.setAttribute('data-index', i);
                    li.addEventListener('click', function() {
                        var index = parseInt(this.getAttribute('data-index'));
                        selectItem(index);
                        var prjName = this.innerText;
                        obj.closeAutoCompleteBox();
                        para.onItemEntered(prjName);
                    });
                    ul.appendChild(li);
                }

                // 获取input的位置
                var dom = document.getElementById(para.domId);
                var rect = dom.getBoundingClientRect();
                var remainHeight = document.body.clientHeight + document.body.scrollTop - dom.offsetTop;
                var bodyMarginLeft = document.body.getBoundingClientRect().left;
                box.style.left = dom.offsetLeft + 'px';

                if (remainHeight > 200) {
                    // 显示在下方
                    box.style.top = (rect.bottom + 1) + 'px';
                    ul.style.maxHeight = (remainHeight - rect.height - 8) + 'px';
                } else {
                    // 显示在上方
                    box.style.bottom = (rect.top + 1) + 'px';
                }
                box.style.width = (rect.width - 4) + 'px';
                // 添加到parent中
                var parent = document.getElementById(para.parentDomId);
                parent.appendChild(box);
                var existed = getExistedDom(para.domId);
                if (existed.func) {
                    dom.removeEventListener('keydown', existed.func);
                }
                existed.func = function(e) {
                    // 监听keydown事件
                    if (e.keyCode === 40) {
                        // 下
                        arrowDown();
                    } else if (e.keyCode === 38) {
                        // 上
                        arrowUp();
                    } else if (e.keyCode === 13) {
                        // 回车
                        if (!ul.childNodes[index]) {
                            console.log('出错了,选择到了错误的index');
                        }
                        var prjName = ul.childNodes[index].innerText;
                        obj.closeAutoCompleteBox();
                        para.onItemEntered(prjName);
                    }
                };
                dom.addEventListener('keydown', existed.func);
                isShow = true; //设置显示状态为show

            },
            "closeAutoCompleteBox": function() {
                var element = document.getElementById('autoCompleteBox');
                if (element) {
                    var parent = element.parentNode.removeChild(element);
                    isShow = false; //设置显示状态为show
                }
            }
        };
        return obj;
    });
});
